package com.cn.main.proxy;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.annotation.Resource;
import java.lang.reflect.Field;

/**
 * @aothor chenyuncong
 * @Date 2022/8/29 下午10:31
 */
public class SpringBean implements ApplicationContextAware {
//    rivate static final Logger log = LoggerFactory.getLogger(SpringBean.class);


    private  static ApplicationContext applicationContext;

    private SpringBean(){}

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBean.applicationContext = applicationContext;
    }

    public static <T> T getSpringBean(Class<T> clazz){
        return SpringBean.applicationContext.getBean(clazz);
    }
    @SuppressWarnings("unchecked")
    public static <T> T getSpringBean(String beanName){
        return (T) SpringBean.applicationContext.getBean(beanName);
    }

    public static void inject(Object object){
        if(object == null)
            return;
        Class clazz = object.getClass();
        while (clazz != Object.class) {
            Field[] fields = clazz.getDeclaredFields();
            System.out.println(clazz);
            for (Field field : fields) {
                Autowired annotation = field.getAnnotation(Autowired.class);
                if (annotation != null) {
//                    Reflector.setFieldValue(object,field,SpringBean.getSpringBean(field.getType()));
                    System.out.println(field.getType());
//
                    SpringBean.getSpringBean(field.getType());
                    System.out.println(SpringBean.getSpringBean(field.getType()));

//                    try {
//                        field.set(object,SpringBean.getSpringBean(field.getType()));
//                    } catch (IllegalAccessException e) {
//                        e.printStackTrace();
//                    }
                }

                Resource resource = field.getAnnotation(Resource.class);
                if (resource != null) {
//                    Reflector.setFieldValue(object,field,SpringBean.getSpringBean(field.getName()));
//                    try {
//                        field.set(object,SpringBean.getSpringBean(field.getType()));
//                    } catch (IllegalAccessException e) {
//                        e.printStackTrace();
//                    }
                }
            }
            clazz = clazz.getSuperclass();
        }
    }

}
